app.controller("editionCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "$filter", "info", function ($scope, $rootScope, $modalInstance, $http, $filter, info) {
    $scope.info = {};
    $scope.info.status = false;
    //选中工程名
    $scope.info.projectName = info.projectName;
    $scope.info.type = info.type;
    //选中工程信息(uplan)
    $scope.info.projectInfo = {};
    //工程版本列表
    $scope.info.editionList = [];
    //选中的版本
    $scope.info.selectEdition = {};
    //sql文件列表
    $scope.info.sqlList = [];
    //配置项列表
    $scope.info.configList = [];
    //其他描述
    $scope.info.otherDesc = '';
    $scope.info.checkAllSql = false;
    $scope.info.checkAllConfig = false;

    $scope.info.isHandelBug = false;

    init();

    function init() {
        var url = beetle_plan_url + "/project/getProjectInfo?token_id=" + getTokenId() + "&project_name=" + $scope.info.projectName;
        $http.get(url).success(function (data) {
            if (!data.success) {
                $rootScope.showMessage("error", "失败", data.msg);
                return false;
            }
            $scope.info.projectInfo = data.data;
            if ($scope.info.projectInfo.isOnBeetle == '1' && $scope.info.projectInfo.package_type != 'ad') {
                $rootScope.showMessage("error", "失败", "工程【" + $scope.info.projectName + "】没有用beetle管理!");
                return false;
            }
            if ($scope.info.projectInfo.package_type == 'maven_jar') {
                $rootScope.showMessage("error", "失败", "jar包工程不需要提交版本！");
                return false;
            }
            if ($scope.info.projectInfo.plan_id == null) {
                $rootScope.showMessage("error", "失败", "工程【" + $scope.info.projectName + "】已经不在任何项目内!");
                return false;
            }
            getProjectEditionList();
        });
    };

    function getProjectEditionList() {
        var url = beetle_plan_url + "/project/getProjectEditionList?token_id=" + getTokenId() + "&project_name=" + $scope.info.projectName;
        $http.get(url).success(function (data) {
            if (!data.success) {
                $rootScope.showMessage("error", "失败", data.msg);
                return false;
            }
            if (data.data.length == 0) {
                $rootScope.showMessage("error", "失败", "工程【" + $scope.info.projectName + "】版本列表为空!");
                return false;
            }
            if ($scope.info.projectInfo.package_type == 'ad') {
                $scope.info.editionList = data.data;
                $scope.info.selectEdition = $scope.info.editionList[0];
            } else {
                //1.提测时，只能选择临时版本提测
                //2.转测时，只能选择临时版本外的版本
                if ($scope.info.type == 'TEST') {
                    if (data.data[0].editionNum != 'default') {
                        $rootScope.showMessage("error", "失败", "工程【" + $scope.info.projectName + "】版本列表为空！");
                        return false;
                    }
                    $scope.info.editionList.push(data.data[0]);
                    $scope.info.selectEdition = $scope.info.editionList[0];
                    if ($scope.info.selectEdition.showNum.indexOf('构建成功') == -1) {
                        return false;
                    }
                } else if ($scope.info.type == 'INTEGRATION') {
                    if (data.data.length == 1) {
                        $rootScope.showMessage("error", "失败", "工程【" + $scope.info.projectName + "没有版本可以转测！");
                        return false;
                    }
                    $scope.info.editionList = data.data;
                    $scope.info.editionList.splice(0, 1);
                    $scope.info.selectEdition = $scope.info.editionList[0];
                } else {
                    return false;
                }
            }
            ;
            $scope.info.status = true;
            if ($scope.info.projectInfo.package_type != 'ad') {
                $scope.getSqlList(true);
            }
        });
    };

    //获取附加说明 查询sql列表、配置列表
    $scope.getSqlList = function (withConfig) {
        if (!$scope.info.status) {
            return false;
        }
        $scope.info.sqlList = [];

        var url = java_url + "/beetle/projectREST/getProjectSqlList?projectName=" + $scope.info.projectName + "&tokenId=" + getTokenId();
        $http.get(url).success(function (data) {
            if (data.code == '0') {
                $scope.info.status = true;
                $scope.info.sqlList = data.data.list;
                angular.forEach($scope.info.sqlList, function (sql) {
                    sql.isCheck = false;
                });
                if (withConfig) {
                    $scope.getConfigList();
                }
            } else {
                $scope.info.status = false;
                $rootScope.showMessage("error", "失败", data.desc);
            }
        }).error(function (result) {
            $scope.info.status = false;
        });
    };

    $scope.getConfigList = function () {
        if (!$scope.info.status) {
            return
        }
        $scope.info.configList = [];

        var url = java_url + "/beetle/projectREST/getProjectConfigList?projectName=" + $scope.info.projectName + "&tokenId=" + getTokenId();
        $http.get(url).success(function (data) {
            if (data.code == '0') {
                $scope.info.status = true;
                $scope.info.configList = data.data.list;
                $scope.editionChange();
            } else {
                $scope.info.status = false;
                $rootScope.showMessage("error", "失败", data.desc);
            }
        }).error(function (result) {
            $scope.info.status = false;
        });
    };

    $scope.downloadSqlFile = function (sql) {
        window.location.href = java_url + "/beetle/projectREST/downloadProjectSql?filePath=" + sql.file_path
            + "&fileName=" + sql.file_name + "&tokenId=" + getTokenId();
    };

    function getTime() {
        var now = new Date();
        var start = null;
        if (now.getHours() < 12) {
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), '00', '00', '00');
        } else {
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), '12', '00', '00');
        }
        return {
            "start": $filter('date')(start, 'yyyy-MM-dd HH:mm:ss'),
            "end": $filter('date')(now, 'yyyy-MM-dd HH:mm:ss')
        }
    }

    $scope.saveClick = function () {
        if ($scope.info.otherDesc == '') {
            $rootScope.showMessage("error", "失败", '提交说明不能为空！');
            return false;
        }

        var config_desc = "";
        var sql_desc = "";
        angular.forEach($scope.info.configList, function (config) {
            if (config.isCheck) {
                config_desc = config_desc + config.fileName + "@@" + config.key + "@@" + config.value + "@@" + config.desc + "##";
            }
        });

        angular.forEach($scope.info.sqlList, function (sql) {
            if (sql.isCheck) {
                sql_desc = sql_desc + sql.file_name + "@@" + sql.file_path + "##";
            }
        });

        //判断是否弹出处理阻断bug弹窗
        var status = ['INTEGRATIONING', 'HAND_OVER', 'ONLINE'];
        if ($scope.info.type == 'INTEGRATION' && arrayContains(status, $scope.info.projectInfo.project_status)) {
            //查询当前时间段是否提交过版本，以中午12点为界，上午提交过版本后再提交为处理阻断bug，下午提交过版本后再提交为处理阻断bug
            var date = getTime();
            console.log(JSON.stringify(date));

            $.ajax({
                type: "get",
                url: beetle_plan_url + '/project/getPHORecordList?token_id=' + getTokenId()
                + '&project_name=' + $scope.info.projectName + '&type=INTEGRATION&start_date=' + encodeURIComponent(date.start) + '&end_date=' + encodeURIComponent(date.end),
                dataType: "JSON",
                async: false,
                success: function (data) {
                    $scope.info.isHandelBug = data.data.length >= 1;
                }
            });
        }

        var param = {
            "project_name": $scope.info.projectName,
            "edition_num": $scope.info.selectEdition.editionNum,
            "type": $scope.info.type,
            "config_desc": config_desc.substring(0, config_desc.length - 2),
            "sql_desc": sql_desc.substring(0, sql_desc.length - 2),
            "other_desc": $scope.info.otherDesc,
            "token_id": getTokenId()
        };

        //提测时，先生成版本 再提测
        if ($scope.info.type == 'TEST' && $scope.info.projectInfo.package_type != 'ad') {
            $http.post(java_url + '/beetle/project/createNewEdition',{
                projectName: $scope.info.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    openDialogAlert(ngDialog, $scope, data.desc);
                    return
                }
                param.edition_num = data.data.editionNum;
                $scope.savePHORecord(param);
            });
        } else if ($scope.info.type == 'INTEGRATION' || ($scope.info.type == 'TEST' && $scope.info.projectInfo.package_type == 'ad')) {
            if ($scope.info.isHandelBug) {
                openDialogText(ngDialog, $scope, "上午/下午已经交付过一次了, 是否是为处理阻塞bug而重新打包？", true, '取消交付', '因为阻塞bug, 需要交付', function (val) {
                    if (!val) {
                        return;
                    }
                    param.is_handle_bug = '0';
                    $scope.savePHORecord(param);
                });
            } else {
                $scope.savePHORecord(param);
            }
        }
    };

    $scope.editionChange = function () {
        if ($scope.info.type == 'TEST' || !$scope.info.status) {
            return false;
        }
        $scope.info.otherDesc = '';
        angular.forEach($scope.info.configList, function (config) {
            config.isCheck = false;
            config.desc = '';
        });
        angular.forEach($scope.info.sqlList, function (sql) {
            sql.isCheck = false;
        });

        if ($scope.info.selectEdition.editionNum == undefined) {
            $scope.info.status = false;
            return false;
        }

        var url = beetle_plan_url + "/project/getPHORecordList?token_id=" + getTokenId() + "&project_name=" + $scope.info.projectName + "&type=TEST&edition_num=" + $scope.info.selectEdition.editionNum;
        $http.get(url).success(function (data) {
            if (data.data.length > 0) {
                var record = data.data[0];
                $scope.info.otherDesc = record.other_desc;
                if (record.config_desc != null) {
                    var configs = record.config_desc.split('##');
                    angular.forEach(configs, function (c) {
                        angular.forEach($scope.info.configList, function (config) {
                            if (c.indexOf(config.fileName + "@@" + config.key + "@@" + config.value + "@@") != -1) {
                                config.isCheck = true;
                                config.desc = c.split('@@')[3];
                            }
                        });
                    });
                }
                angular.forEach($scope.info.sqlList, function (sql) {
                    if (record.sql_desc.indexOf(sql.file_name + "@@" + sql.file_path) != -1) {
                        sql.isCheck = true;
                    }
                });
            }
        });
    };

    //全选
    $scope.checkAll = function (type) {
        if (type == 'sql') {
            angular.forEach($scope.info.sqlList, function (sql) {
                sql.isCheck = $scope.info.checkAllSql;
            });
        } else if (type == 'config') {
            angular.forEach($scope.info.configList, function (config) {
                config.isCheck = $scope.info.checkAllConfig;
            });
        }
    };

    $scope.savePHORecord = function (data) {
        var url = beetle_plan_url + "/project/savePHORecord";
        $http({
            method: "post",
            url: url,
            data: data,
            headers: "json"
        }).success(function (result) {
            if (result.success) {
                //提交成功后 关闭弹窗
                $modalInstance.close(result.data);
            } else {
                $rootScope.showMessage("error", "失败", result.msg);
            }
        });
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
